package cc.realxyq.springboot.db.mongodb.dao.impl;

import cc.realxyq.springboot.db.mongodb.baens.MongoUser;
import cc.realxyq.springboot.db.mongodb.dao.MongoDbUserDao;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @author : [buleing]
 * @version : [v1.0]
 * @description : [一句话描述该类的功能]
 * @createTime : [2021/6/11 17:07]
 * @updateUser : [buleing]
 * @updateTime : [2021/6/11 17:07]
 * @updateRemark : [说明本次修改内容]
 */

@Component
public class MongoDbUserDaoImpl implements MongoDbUserDao {

    @Resource
    private MongoTemplate mongoTemplate;
    @Override
    public MongoUser save(MongoUser user) {
        return mongoTemplate.save(user);
    }

    @Override
    public DeleteResult delete(MongoUser user) {

        Query query=new Query(Criteria.where("id").is(user.getUserId()));
        return mongoTemplate.remove(query,MongoUser.class);
    }

    @Override
    public Long update(MongoUser user) {
        Query query=new Query(Criteria.where("id").is(user.getUserId()));
        Update update = new Update().set("avatar",user.getAvatar()).set("name",user.getName());
        UpdateResult result =mongoTemplate.updateFirst(query,update,MongoUser.class);

        //mongoTemplate.updateMulti(query,update,MongoUser.class);
        return null==result?0:result.getMatchedCount();
    }

    @Override
    public List<MongoUser> findByName(MongoUser user) {
        Query query = new Query(Criteria.where("name").is(user.getName()));
        List<MongoUser> list = mongoTemplate.find(query,MongoUser.class);
        return null==list?Collections.emptyList():list;
    }
}
